package com.kexun.webSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kexun.common.utils.HttpUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/messageServer/{userId}")
@Component
public class WebSocketServer {
    private static Logger logger = Logger.getLogger(WebSocketServer.class);
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    @Value("${server.port}")
    private int port;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        logger.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());

    }

    @OnClose
    public void onClose() throws IOException {
        if (webSocketMap.containsKey(userId)) {
            //告诉监控平台断开连接
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        logger.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
//        logger.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (!StringUtils.isEmpty(message)) {
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("from", this.userId);
                String to = jsonObject.getString("to");
                //传送给对应toUserId用户的websocket
                if (!StringUtils.isEmpty(to) && webSocketMap.containsKey(to)) {
                    webSocketMap.get(to).sendMessage(jsonObject.toJSONString());
                } else {
                    logger.info("请求的userId:" + to + "不在该服务器上");
                    //否则不在这个服务器上，发送到mysql或者redis
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) {
        synchronized (session) {
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 发送自定义消息
     */
    public void sendInfo(String message, String userId) {
        logger.info("发送消息到:" + userId + "，报文:" + message);
        logger.info("在线用户:" + webSocketMap);
        if (!StringUtils.isEmpty(userId)) {
            if (webSocketMap.containsKey(userId)) {
                webSocketMap.get(userId).sendMessage(message);
                logger.info(">>用户存在" + userId + "发送消息");
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId", userId);
                jsonObject.put("message", message);
                jsonObject.put("token", "0c8534b8a5a54f7a9a4fe7581cb97d63");
                int pushPort = port == 9999 ? 9998 : 9999;
                logger.info("用户" + userId + "不存在推送到" + pushPort + "节点");
                HttpUtils.doPostJson("http://127.0.0.1:" + pushPort + "/message/retrySend", jsonObject.toJSONString());
            }
        } else {
            logger.info("用户" + userId + ",不在线！");
        }
    }


    public void retrySend(String message, String userId) {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            logger.info("用户" + userId + ",不在线！");
        }

    }

    /**
     * 群发消息
     *
     * @param message
     * @throws IOException
     */
    public static void sendAll(String message) throws IOException {
        logger.info("群发消息:" + message);
        Set<Map.Entry<String, WebSocketServer>> entries = webSocketMap.entrySet();
        for (Map.Entry<String, WebSocketServer> entry : entries) {
            WebSocketServer socketServer = entry.getValue();
            socketServer.sendMessage(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
